<template>
  <div class="h-full flex flex-col">
    <div class="flex flex-between items-center p-2 mb-2 border-b">
      <div>
        <a-input-search v-model:value="searchKey" class="w-64" placeholder="姓名/助记码/床位号" @search="getData" />
        <a-range-picker
          v-if="store.insiedShowType === 1"
          v-model:value="dateRange"
          allow-clear
          class="w-64 ml-2"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="getData()"
        />
      </div>
      <div v-if="levelCount.length > 0" class="flex border border-dashed border-gray-300 rounded-full px-12 py-1">
        <a-space :size="20">
          <div v-for="level in levelCount" :key="level" class="flex-center">
            <NurseLevelIcon :icon-code="level.iconCode" />
            <span class="font-bold ml-1"> {{ level.hzs || 0 }}人</span>
          </div>
        </a-space>
      </div>
      <div class="flex justify-end items-center">
        <div>隐藏空床</div>
        <a-switch v-model:checked="store.cardSwitch" class="ml-1 mr-3" @change="getData" />
        <a-button type="primary" ghost class="ml-1 mr-3" :disabled="!selectedRowKeys.length" @click="onPrintBedCardBatch"
          ><BaseIcon name="PrinterOutlined" />打印床卡</a-button
        >
        <BaseExport
          type="住院"
          name="在区"
          code="000091"
          class="my-1"
          :search-params="{
            statuss: [0, 2],
            bqbh: store.areaCode,
            pyjm: searchKey,
            lastDeptRegTimeStart: store.insiedShowType === 1 ? dateRange?.[0] : undefined,
            lastDeptRegTimeEnd: store.insiedShowType === 1 ? dateRange?.[1] : undefined
          }"
          >导出</BaseExport
        >
        <div class="absolute top-[-9999px] hidden">
          <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
          <a-button ref="printMeBeb" v-print="{ id: 'printMeBeb' }">打印</a-button>
          <PrintView id="printMe" :print-data="printData" />
          <PrintViewBeb id="printMeBeb" :print-data="printData" />
        </div>
      </div>
    </div>
    <BaseTable
      v-if="store.insiedShowType === 1"
      column-code="000091"
      row-key="inplsh"
      :loading="loading"
      :scroll="{ x: 2600 }"
      :data-source="tableData"
      fill
      :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'xh'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'status'">
          <a-tag color="blue">{{ ['在院', '已出院', '待出院', '待入区', '作废'][record.status] }}</a-tag>
        </template>
        <template v-if="column.dataIndex === 'brName'">
          <InPatientPopover
            v-model:open="record.openPopover"
            is-modify
            :patient-info="record"
            @change="getData"
            @click="record.openPopover = !record.openPopover"
          >
            <div class="cursor-pointer text-primary hover:underline">{{ record.brName }}</div>
          </InPatientPopover>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <BaseButton type="link" size="small" @click="onAction('换床', record)"> 换床 </BaseButton>
          <BaseButton type="link" size="small" @click="onClickBook(record)"> 费用记账 </BaseButton>
          <BaseButton type="link" size="small" @click="openReplace(record)"> 更换医护 </BaseButton>
          <a-dropdown>
            <BaseButton type="link" size="small" :icon="h(EllipsisOutlined)" />
            <template #overlay>
              <a-menu>
                <a-menu-item @click="onAction('更换护理等级', record)">
                  <span class="text-primary"> 更换护理等级 </span>
                </a-menu-item>
                <a-menu-item v-if="record.inpDischarge" @click="onDischarge(record)">
                  <span class="text-primary"> 通知出院 </span>
                </a-menu-item>
                <a-menu-item v-if="record.inpTransferZone" @click="onAction('转区', record)">
                  <span class="text-primary"> 转区 </span>
                </a-menu-item>
                <!-- <a-menu-item>
                  <BaseButton type="link" size="small" @click="openReplace(record)"> 更换医护 </BaseButton>
                </a-menu-item> -->
                <a-menu-item @click="onPrint(record)">
                  <span class="text-primary">床卡</span>
                </a-menu-item>
                <a-menu-item @click="onPrintWrist(record)">
                  <span class="text-primary">腕带</span>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </template>
    </BaseTable>
    <div v-else class="flex flex-1 overflow-hidden">
      <div v-if="tableData.length" class="h-full w-full flex flex-wrap overflow-y-auto content-start pb-[60px]">
        <div class="bg-white p-2 absolute bottom-0 w-full flex items-center z-20">
          <a-input v-model:value="wardMemo" class="mr-2" placeholder="请输入今日住院须知" />
          <a-button type="primary" @click="onSaveWardMemo">保存</a-button>
        </div>
        <template v-for="item in tableData" :key="item?.inplsh">
          <a-dropdown v-if="item.inplsh" class="h-fit" trigger="contextmenu">
            <BedCard
              class="m-2"
              :data="item"
              show-footer
              is-modify
              :active="currentBed?.inplsh === item?.inplsh"
              @click="onRightClick(item)"
              @contextmenu.prevent.stop="onRightClick(item)"
              @change="onSuccess"
            />
            <!-- 右键菜单 -->
            <template #overlay>
              <a-menu selectable multiple :selected-keys="item.highRiskCodes || []">
                <a-menu-item key="1-1" @click="onAction('换床', item)">换床</a-menu-item>
                <a-menu-item key="2-1" @click="onAction('更换护理等级', item)">更换护理等级</a-menu-item>
                <a-menu-item key="3-1" @click="openReplace(item)">更换医护</a-menu-item>
                <a-menu-item v-if="item.inpDischarge" key="4-1" @click="onDischarge(item)">通知出院</a-menu-item>
                <a-menu-item v-if="item.inpTransferZone" key="5-1" @click="onAction('转区', item)">转区</a-menu-item>
                <a-divider class="my-0" />
                <a-menu-item key="6-1" @click="onClickBook(item)">费用记账</a-menu-item>
                <a-menu-item key="7-1" @click="onClickExpense(item)">费用核对</a-menu-item>
                <a-menu-item key="9-1" @click="onAction('每日清单', item)">每日清单</a-menu-item>
                <a-menu-item key="10-1" @click="onOpenPayModal(item)">催款单</a-menu-item>
                <a-divider class="my-0" />
                <a-menu-item key="11-1" @click="onAction('血糖监测', item)">血糖监测</a-menu-item>
                <a-menu-item key="12-1" @click="onClickTemperature(item)">体温脉搏单</a-menu-item>
                <a-menu-item key="13-1" @click="onClickNuringRecord(item)">护理记录单</a-menu-item>
                <a-sub-menu v-if="riskData.length > 0" key="14-1" title="标记高危">
                  <a-menu-item v-for="items in riskData" :key="items.dictItemCode" @click="onClickRisk(items.dictItemCode, item)">{{
                    items.dictItemName
                  }}</a-menu-item>
                </a-sub-menu>
                <a-divider class="my-0" />
                <a-menu-item key="15-1" @click="onPrint(item)">床卡</a-menu-item>
                <a-menu-item key="16-1" @click="onPrintWrist(item)">腕带</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          <a-dropdown v-else class="h-fit" trigger="contextmenu">
            <BedCardEmpty class="m-2" :bed-code="item.bedCode" :room-name="item.roomName" />
            <!-- 右键菜单 -->
            <template #overlay>
              <a-menu>
                <a-menu-item @click="onRegistration(item)">入区登记</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </div>
      <div v-else class="w-full h-full flex-center">
        <a-empty />
      </div>
      <a-spin v-if="loading" :spinning="loading" class="w-full h-full flex-center absolute" />
    </div>
    <OperateModal v-model:open="modalStatus.open" :data="currentBed" :type="modalStatus.type" @success="onSuccess" @close="currentBed = {}" />
    <EnterModal v-model:open="registrationOpen" :row-data="registrationRow" @success="onSuccess" />
    <ReplaceDoctor v-model:open="replaceModal" :data="currentBed" @success="onSuccess" />
    <!-- 催款单 -->
    <DemandModal
      v-model:open="depositModal"
      :patient-info="{ ...patientInfo, deJeCount: patientInfo.dpJe, settlementAmount: patientInfo.zyfy, wardName: patientInfo.wardName }"
      @success="getData"
    />
  </div>
</template>
<script setup>
import { reactive, ref, watchEffect, h, createVNode } from 'vue'
import { message } from 'ant-design-vue'
import { EllipsisOutlined } from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import BedCard from '@/components/business/BedCard'
import BedCardEmpty from '@/components/business/BedCard/BedCardEmpty'
import InPatientPopover from '@/components/InPatientPopover'
import { post, get } from '@/utils/request'
import DemandModal from '@/views/in-registration/components/DemandModal.vue'
import { getSystemConfig } from '@/utils/systemConfig'
import useStore from '../../store'
import EnterModal from '../component/EnterModal'
import PrintView from '../component/PrintView.vue'
import PrintViewBeb from '../component/PrintViewBeb.vue'
import OperateModal from './OperateModal.vue'
import ReplaceDoctor from './ReplaceDoctor.vue'

const store = useStore()
const riskData = ref([])
const router = useRouter()
const modalStatus = reactive({ open: false, type: '' })
const registrationOpen = ref(false)
const replaceModal = ref(false)
const registrationRow = ref({})
const currentBed = ref({})
const searchKey = ref('')
const dateRange = ref([])
const levelCount = ref([])
const selectedRowKeys = ref([])
const depositModal = ref(false)
const patientInfo = ref({})
const printData = ref({})
const printMe = ref()
const printMeBeb = ref()

const onRegistration = (row) => {
  registrationRow.value = { ...row, isBedCode: true }
  registrationOpen.value = true
}

const { loading, tableData, getData } = useTable({
  url: store.insiedShowType === 1 ? '/inp/zydj/getInpRecordList' : '/inp/zyhs/getCwAndInpRecordList',
  immediate: true,
  pagination: false,
  formatParams: () => {
    return {
      statuss: [0, 2],
      bqbh: store.areaCode,
      pyjm: searchKey.value,
      hiddenEmptyBed: store.cardSwitch,
      lastDeptRegTimeStart: store.insiedShowType === 1 ? dateRange.value?.[0] : undefined,
      lastDeptRegTimeEnd: store.insiedShowType === 1 ? dateRange.value?.[1] : undefined
    }
  },
  onSuccess: () => {
    tableData.value.forEach((item) => (item.openPopover = false))
  }
})

const onRightClick = (bed) => {
  currentBed.value = bed
}

const onSuccess = () => {
  getLevelCount()
  getData()
}

const onClickRisk = async (val, item) => {
  const highRiskCodes = item.highRiskCodes || []

  if (highRiskCodes?.length > 0 && highRiskCodes.includes(val)) {
    const index = highRiskCodes.indexOf(val)
    highRiskCodes.splice(index, 1)
  } else {
    highRiskCodes.push(val)
  }
  const riskCode = highRiskCodes?.join(',')
  const { msg, code } = await post('/inp/zydj/flagHighRisk', { highRiskCode: riskCode, inplsh: item.inplsh })
  if (code !== 0) message.error(msg)
  getData()
}

const getRiskData = async () => {
  const { data = [], code } = await post('/operation/opex/getDictCommonItemList', { dictCommonCode: 'DT00314', status: 1 })
  if (code === 0) {
    riskData.value = data
  }
}

const getLevelCount = async () => {
  const { code, data } = await get('/inp/zyhs/getPatientCountbyNursingGradeList?bqbh=' + store.areaCode)
  if (code === 0) {
    levelCount.value = data
  }
}
watchEffect(() => {
  getLevelCount()
})
const onAction = (type, row) => {
  currentBed.value = row
  modalStatus.type = type
  modalStatus.open = true
}
const openReplace = (row) => {
  currentBed.value = row
  replaceModal.value = true
}

//出院
const onDischarge = async (row) => {
  Modal.confirm({
    title: '提示',
    okText: '确定',
    centered: true,
    maskClosable: true,
    width: 560,
    cancelText: '取消',
    icon: createVNode(ExclamationCircleOutlined, { style: 'color:red' }),
    content: createVNode('div', { style: 'margin:24px 0;font-size:15px' }, '确定通知出院？'),
    onOk: async () => {
      const { code, msg } = await post('/inp/zyys/doNoticeOfDischarge', {
        inplsh: row.inplsh,
        advId: row.inpDischarge?.inpAdvId
      })
      if (code !== 0) return message.error(msg || '操作失败')
      message.success(msg || '通知出院成功')
      store.getStatusCount()
      onSuccess()
    }
  })
}
const onSelectChange = (keys) => {
  selectedRowKeys.value = keys
}
// 床卡打印
const onPrintBedCardBatch = async () => {
  const { code, msg, data } = await post('/inp/Print/batchBedCardPrint', {
    inplshs: selectedRowKeys.value
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
// 床卡打印
const onPrint = async (row) => {
  const { code, msg, data } = await post('/inp/Print/bedCardPrint', {
    inplsh: row.inplsh
  })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      printMeBeb.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}

// 腕带
const onPrintWrist = async (row) => {
  const { code, msg, data } = await post('/inp/Print/inpWristbandsPrint', {
    inplsh: row.inplsh
  })
  if (code !== 0) return message.error(msg)

  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      printMe.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}
//住院须知
const wardMemo = ref('')
const onSaveWardMemo = async () => {
  if (!wardMemo.value) return message.error('请输入今日住院须知')
  const { code, msg } = await post('/inp/zyhs/updateWardMemo', {
    memo: wardMemo.value,
    wardId: store.areaCode
  })
  if (code !== 0) return message.error(msg)
  message.success(msg || '保存住院须知成功')
}
const onQueryWardMemo = async () => {
  const { code, msg, data } = await post('/inp/zyhs/queryWardMemo', {
    wardId: store.areaCode
  })
  if (code !== 0) return message.error(msg)
  wardMemo.value = data
}

// 费用记账-跳转补记账
const onClickBook = (row) => {
  router.push({
    path: '/in-nurse/patient-management/billing',
    query: {
      inplsh: row.inplsh
    }
  })
}
//  费用核对-跳转费用核对
const onClickExpense = (row) => {
  router.push({
    path: '/in-nurse/patient-management/expense-reconciliation',
    query: {
      inplsh: row.inplsh
    }
  })
}
// 体温脉搏单-跳转体温脉搏单
const onClickTemperature = (row) => {
  router.push({
    path: '/in-nurse/nursing/temperature-pulse',
    query: {
      inplsh: row.inplsh
    }
  })
}
// 护理记录单-跳转护理记录单
const onClickNuringRecord = (row) => {
  router.push({
    path: '/in-nurse/nursing/nursing-record',
    query: {
      inplsh: row.inplsh
    }
  })
}

const onOpenPayModal = (item) => {
  patientInfo.value = item
  depositModal.value = true
}
onMounted(() => {
  getRiskData()
  onQueryWardMemo()
})
</script>
